import { Kwidget } from "../kWidget";
import { getIconByName } from "./config"
class Kicon extends Kwidget {

    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.render();
        this.svg = this.shadowRoot.querySelector('svg');
    }

    static get observedAttributes() {
        return ['name','size','color'];
    }

    connectedCallback() {
        this.logInfo('k-icon挂载成功');       
    }

    attributeChangedCallback(name, oldValue, newValue) {
        switch (name) {
            case 'size':
                this.setIconSize(newValue);
                break;
            case 'color':
                this.setIconColor(newValue);
                break;
            default:
                break;
        }
    }

    setIconSize() {
        try {
            this.svg.setAttribute('width', this.size);
            this.svg.setAttribute('height', this.size); 
        } catch (error){
            throw new Error('出错啦' + error);

        }
    }

    setIconColor(color) {
        if (!this.svg) throw new Error('svg not found');
        this.svg.setAttribute('fill', color ? color : this.color);
    }

    get color() {
        return this.getAttribute('color') || '#ff0000';
    }

    set color(value) {
        this.setAttribute('color', value);
    }

    get size() {
        return this.getAttribute('size') || 20;
    }

    set size(value) {
        this.setAttribute('size', value);
    }

    get name() {
        return this.getAttribute('name');
    }

    set name(value) {
        this.setAttribute('name', value);
    }

    render() {
        const template = document.createElement('template');
        template.innerHTML = `
           ${getIconByName(this.name)}
        `;
        this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
}

if (customElements.get("k-icon") == undefined) {
    customElements.define("k-icon", Kicon);
}

export { Kicon };